package com.bitauto.i.commonUtils.leet;

public class Answer29 {

    public int divide(int dividend, int divisor) {
        int ans = 0;
        int sign = 1;
        if (dividend < 0) {
            sign = opposite(sign);
            dividend = opposite(dividend);
        }
        if (divisor < 0) {
            sign = opposite(sign);
            divisor = opposite(divisor);
        }
        while (divisor <= dividend) {
            ans = ans + 1;
            dividend = dividend - divisor;
        }
        return sign > 0 ? ans : opposite(ans);
    }

    public int opposite(int x) {
        return ~x + 1;
    }


    public int divide2(int dividend, int divisor) {
        int ans = 0;
        int sign = 1;

        if (dividend < 0) {
            sign = opposite(sign);
            dividend = opposite(dividend);
        }
        if (divisor < 0) {
            sign = opposite(sign);
            divisor = opposite(divisor);
        }
        //单独判断一下
        if (dividend == Integer.MIN_VALUE && divisor == 1) {
            return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        }
        while (divisor <= dividend) {
            ans = ans + 1;
            dividend = dividend - divisor;
        }
        return sign > 0 ? ans : opposite(ans);
    }

    public int opposite2(int x) {
        return ~x + 1;
    }


    public int divide3(int dividend, int divisor) {
        int ans = 1;
        int sign = 1;
        if (dividend < 0) {
            sign = opposite(sign);
            dividend = opposite(dividend);
        }
        if (divisor < 0) {
            sign = opposite(sign);
            divisor = opposite(divisor);
        }
        if (dividend == Integer.MIN_VALUE && divisor == 1) {
            return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        }
        int origin_dividend = dividend;
        int origin_divisor = divisor;
        //由于 ans 初始值是 1 ，所以如果被除数小于除数直接返回 0
        if (dividend < divisor) {
            return 0;
        }
        dividend -= divisor;
        while (divisor <= dividend) {
            ans = ans + ans;
            divisor += divisor;
            dividend -= divisor;
        }
        int a = ans + divide(origin_dividend - divisor, origin_divisor);
        return sign > 0 ? a : opposite(a);
    }
    public int opposite3(int x) {
        return ~x + 1;
    }


}
